package com.rykj.energy.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class SysConfig {
    private static SysConfig context = null;
    Properties prop = null;
    private static byte[] lock = new byte[0];
    private SysConfig() {
        init();        
    }
    
    private void init() {
        load();
    }
    
    private static SysConfig getInstance() {
        
        synchronized (lock) {
            if(context == null) {
                context = new SysConfig();
            }
        }
        return context;
    }
    
    public String getProperty(String key) {
        return getProperty(key, null);
    }
    
    public String getProperty(String key, String defaultValue) {
        return getInstance().prop.getProperty(key, defaultValue);
    }
        
    private String load() {
        String loadFile = null;
        prop = new Properties();
        loadFile = "server.properties";
        InputStream in = SysConfig.class.getClassLoader().getResourceAsStream("server.properties");
        
        if (in == null) {
            log.warn("server.properties is not found, System is looking for default.properties");
            in = SysConfig.class.getClassLoader().getResourceAsStream("default.properties");
            loadFile = "default.properties";
        }           
        try {
            prop.load(in);
        } catch (NullPointerException e) {
            loadFile = null;
            log.error("system cann't find configuration,please check *.properties");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
        return loadFile;
    }   
        

    public static String getValue(String key, String defaultValue) {
        return getInstance().getProperty(key, defaultValue);
    }
}
